import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/pick/ai/ai_model_logic.dart';
import 'package:ball_lion/entity/ai/ai_combo_entity.dart';
import 'package:ball_lion/entity/ai/ai_item_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/entity/ai/ai_pay_entity.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/module/pick/ai/ai_type.dart';

class AiComboItem extends StatelessWidget {
  const AiComboItem(
      {super.key,
      required this.item,
      this.onChange,
      this.margin,
      this.onTap,
      this.logic});

  final DetailItems item;
  final EdgeInsets? margin;
  final AiModelLogic? logic;
  final ValueChanged<bool>? onChange;
  final Function()? onTap;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Block(
            onTap: () => onTap?.call(),
            cardStyle: CardStyle(
                margin: margin ?? const EdgeInsets.only(bottom: 12),
                padding: const EdgeInsets.fromLTRB(12, 8, 12, 0)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        QsText(item.title ?? ""),
                        if (item.isOpen == 0 || item.hit == 3)
                          QsText("预计最高回报${item.profit ?? ""}",
                                  fontSize: 12, color: Colours.grey99)
                              .paddingOnly(top: 4)
                      ],
                    ),
                    if (!item.hit.hasValue)
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          RatingBar(
                              initialRating: item.level?.toDouble() ?? 0,
                              allowHalfRating: true,
                              itemCount: 5,
                              itemSize: 16,
                              ignoreGestures: true,
                              unratedColor: Colours.grey99,
                              ratingWidget: RatingWidget(
                                  full: Image.asset(
                                      width: 16,
                                      color: Colours.main,
                                      Utils.getImgPath(
                                          "match_info_star_on.png")),
                                  half: Image.asset(
                                      width: 16,
                                      Utils.getImgPath(
                                          "match_info_star_half.png")),
                                  empty: Image.asset(
                                      width: 16,
                                      Utils.getImgPath(
                                          "match_info_star_off.png"))),
                              onRatingUpdate: (rating) => 0),
                          Container(height: 6),
                          QsText(item.levelCont ?? "",
                              fontSize: 12, color: Colours.grey99)
                        ],
                      )
                  ],
                ),
                Container(height: 8),
                ...item.items
                        ?.map((e) => matchItem(e))
                        .toList()
                        .insertEvery(Container(height: 8)) ??
                    [],
                if (item.isOpen != 1 && !item.hit.hasValue) ...[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(width: 16, Utils.getImgPath("ai_lock.png")),
                      Container(width: 4),
                      QsText(
                          item.priceId.hasValue
                              ? "${item.price?.changeUnit.trim()}解锁"
                              : "立即开通",
                          color: Colours.main,
                          fontWeight: FontWeight.w500),
                    ],
                  ).paddingSymmetric(vertical: 6).tap(() async {
                    onTap?.call();
                    await User.needLogin(() async {
                      if (item.priceId.hasValue) {
                        await logic?.toPay(AiPrice(
                            id: item.priceId,
                            price: item.price == "会员免费" ? "0" : item.price,
                            aiId: item.aiId));
                      } else {
                        Get.toNamed(Routes.aiPay, arguments: AiType.combo.tag)
                            ?.then((value) => onChange?.call(true));
                      }
                    });
                  })
                ] else ...[
                  Container(height: 16)
                ]
              ],
            )),
        if (item.hit.hasValue && item.hit! > 1 && item.hit! < 4) ...[
          Positioned(
              right: 0,
              top: 0,
              child: Image.asset(Utils.getImgPath("ai_tag.png"), height: 20)),
          Positioned(
            top: 0,
            right: 0,
            child: Container(
              width: 73,
              height: 18,
              alignment: Alignment.center,
              child: QsText(
                item.hit == 2 ? "2中1" : "中",
                fontSize: 12,
                color: Colours.white,
              ),
            ),
          )
        ]
      ],
    );
  }

  Widget matchItem(AiItemEntity entity) {
    return Container(
        padding: const EdgeInsets.fromLTRB(12, 12, 12, 0),
        decoration: BoxDecoration(
            color: Colours.greyF7FAFF, borderRadius: BorderRadius.circular(6)),
        child: Column(
          children: [
            DefaultTextStyle(
              style: const TextStyle(color: Colours.grey66, fontSize: 11),
              child: GestureDetector(
                onTap: () => Get.toNamed(Routes.leagueDetail,
                    arguments: "${entity.leagueId}"),
                child: Row(
                  children: [
                    QsText(entity.leagueName ?? ""),
                    Container(width: 6),
                    QsText(
                      DateTime.tryParse(entity.matchTime ?? "")
                          ?.formatedString("MM-dd HH:mm"),
                      height: 1.2,
                    ),
                    Container(width: 6),
                    QsText(logic?.ticketName(entity) ?? (entity.matchNo ?? ""))
                  ],
                ),
              ),
            ),
            Container(height: 8),
            GestureDetector(
              onTap: () =>
                  Get.toNamed(Routes.zqMatchDetail, arguments: entity.matchId),
              child: Row(
                children: [
                  Expanded(
                      flex: 3,
                      child: teamInfo(entity.homeLogo, entity.homeName,
                          entity.homeRanking, false)),
                  Expanded(
                      flex: 1,
                      child: score(entity.homeScore90, entity.guestScore90)
                          .center),
                  Expanded(
                      flex: 3,
                      child: teamInfo(entity.guestLogo, entity.guestName,
                          entity.guestRanking, true)),
                ],
              ),
            ),
            Container(height: 8),
            if (item.isOpen == 1 || item.hit.hasValue) ...[
              const Divider(color: Colours.greyDD, height: 0.5),
              option(entity.aiOption).paddingOnly(top: 6, bottom: 2)
            ],
            Container(height: 4)
          ],
        ));
  }

  Widget teamInfo(String? logo, String? name, String? rank, bool reverse) {
    List<Widget> info = [
      CachedNetworkImage(
          width: 28,
          height: 28,
          placeholder: (context, url) => Styles.placeholderIcon(),
          errorWidget: (
            context,
            url,
            error,
          ) =>
              Image.asset(Utils.getImgPath("zq_placeholder.png")),
          imageUrl: logo ?? ""),
      Container(width: 8),
      Flexible(
        child: QsText(name ?? "", fontWeight: FontWeight.w500),
      ),
      Container(width: 2),
      if (rank.hasValue) QsText("[$rank]", fontSize: 11, color: Colours.grey99)
    ];
    return Row(
        mainAxisAlignment:
            reverse ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: reverse ? info.reversed.toList() : info);
  }

  Widget score(int? home, int? guest) {
    return DefaultTextStyle(
      style: const TextStyle(
          fontSize: 14, fontWeight: FontWeight.w500, color: Colours.grey66),
      child: home != null && guest != null
          ? QsText("$home : $guest")
          : QsText("vs"),
    );
  }

  Widget option(List<AiOption>? option) {
    List<String> text = [];
    option?.forEach((element) {
      if (element.option.hasValue && element.odds.hasValue) {
        text.add("${element.option} ${element.odds?.split("指数").join("")}");
      }
    });
    return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: List<Widget>.generate(
            text.length,
            (index) => QsText(text[index],
                color:
                    option?[index].hit == true ? Colours.main : Colours.grey66,
                fontWeight: FontWeight.w500)).insertEvery(Container(width: 6)));
  }
}
